<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Project as ProjectModel;
use app\admin\model\Category;
use app\admin\model\ProjectAssign;
use app\admin\model\User;
use app\common\model\TipMsg;
use think\Db;
use app\admin\model\Category as AdminCategoryModel;

/**
 * 项目管理
 *
 * @icon fa fa-circle-o
 */
class Project extends Backend
{
    
    /**
     * Project模型对象
     * @var \app\admin\model\Project
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Project;
        $this->view->assign("pstateList", $this->model->getPstateList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            if ($list) {
                foreach ($list as &$listVal) {
                    $categoryIds = $listVal['category_ids'] ? explode(',', $listVal['category_ids']) : '';
                    $categoryNames = [];
                    if ($categoryIds) {
                        $categorys = Category::findListByCondition(['id' => ['in', $categoryIds]]);
                        if ($categorys) {
                            foreach ($categorys as $categoryVal) {
                                $categoryNames[] = $categoryVal['name'];
                            }
                        }
                    }
                    $listVal['category_names'] = $categoryNames ? implode(',', $categoryNames) : '';
                }
            }

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 获取人才列表
     */
    public function categories()
    {
        $projectId = $this->request->param('project_id', 0);
        if ($projectId > 0) {
            //获取项目详情数据
            $project = ProjectModel::findInfoByCondition(['id' => $projectId]);
            if ($project) {
                $list = ProjectAssign::findListByCondition(['project_id' => $projectId, 'is_del' => 0]);
                $dategoryData = [];
                if ($list) {
                    foreach ($list as $listVal) {
                        $category = Category::findInfoByCondition(['id' => $listVal['category_id']]);

                        $assignUserName = '';
                        if ($listVal['uid']) {
                            $assignUser = User::findInfoByCondition(['id' => $listVal['uid']]);
                            $assignUserName = $assignUser['hua_name'] ? $assignUser['hua_name'] : ($assignUser['nickname'] ? $assignUser['nickname'] : ($assignUser['username'] ? $assignUser['username'] : ''));
                        }

                        $workStatus = '';
                        $listVal['work_status'] = intval($listVal['work_status']);
                        if ($assignUserName) {  //有分配
                            switch ($listVal['work_status']) {
                                case 2:
                                    $workStatus = '已完成';
                                    break;
                                case 1:
                                    $workStatus = '工作中';
                                    break;
                                case 0:
                                    $workStatus = '未开始';
                                    break;
                                case 3:
                                    $workStatus = '已退出';
                                    break;
                            }
                        }

                        $data = [
                            'category_id' => $listVal['category_id'],
                            'name' => $category['name'],
                            'assign_user' => $assignUserName,
                            'assign_status' => $assignUserName ? '已匹配' : '未匹配',
                            'assign_time' => $listVal['assign_time'] ? date('Y-m-d H:i:s', $listVal['assign_time']) : '',
                            'work_status_name' => $workStatus,
                            'work_status' => (int)$listVal['work_status'],
                            'employ_price' => $listVal['employ_price'],
                            'is_charge' => $listVal['is_charge'],
                            'is_charge_name' => $listVal['is_charge'] ? '是' : '否',
                            'is_assign' => $assignUserName ? 1 : 0,
                            'id' => $listVal['id']
                        ];

                        $dategoryData[] = $data;
                        unset($data);
                        unset($assignUser);
                        unset($category);
                    }

                    return json(array("total" => count($dategoryData), "rows" => $dategoryData));
                }

                unset($dategoryData);
            }
        }

        return json(array("total" => 0, "rows" => []));
    }

    public function assignUser()
    {
        $assignId = $this->request->param('ids', 0);
        //获取项目分配记录
        $projectAssign = ProjectAssign::findInfoByCondition(['id' => $assignId]);

        //获取岗位列表
        $categories = Category::findListByCondition(['type' => 'default']);
        $categoryList = [];
        if ($categories) {
            foreach ($categories as $categoryItem) {
                $categoryList[$categoryItem['id']] = $categoryItem['name'];
            }
        }
        $categoryList[0] = "请选择";

        // 工作状态
        $workStatus = [
            '0' => '请选择',
            '1' => '空闲中',
            '2' => '工作中',
            '3' => '已结束',
            '4' => '已退出'
        ];

        // 传递配置给js
        $this->assignconfig('project', ['id' => $projectAssign['project_id'], 'category_id' => $projectAssign['category_id'], 'assign_id' => $assignId, 'categories' => json_encode($categoryList, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)]);

        $this->assign('categories', $categoryList);
        $this->assign('workStatus', $workStatus);

        return $this->view->fetch('assign_user');
    }

    public function doassign()
    {
        $assignId = $this->request->param('assign_id', 0);
        if ($assignId <= 0) {
            return json(['msg' => '参数错误', 'code' => 0]);
        }
        $userId = $this->request->param('ids', 0);
        if ($userId <= 0) {
            return json(['msg' => '用户不存在', 'code' => 0]);
        }
        $assign = ProjectAssign::findInfoByCondition(['id' => $assignId]);
        if (!$assign) {
            return json(['msg' => '参数错误', 'code' => 0]);
        }
        $repeat = ProjectAssign::findInfoByCondition(['uid' => $userId, 'project_id' => $assign['project_id']]);
        if ($repeat) {
            return json(['msg' => '不能重复指派', 'code' => 0]);
        }

        //判断是否已经这是雇佣价格
        if ($assign['employ_price'] <= 0) {
            return json(['msg' => '请设置分配的雇佣价格', 'code' => 0]);
        }

        ProjectAssign::saveData(['id' => $assignId], ['uid' => $userId, 'assign_time' => time(), 'work_status' => 1]);

        // 用户状态变为工作中
        User::saveData(['id' => $userId], ['state' => 1]);

        //加入消息滚动
        $user = User::findInfoByCondition(['id' => $userId]);
        $project = \app\admin\model\Project::findInfoByCondition(['id' => $assign['project_id']]);
        $msgContent = "恭喜{$user['hua_name']}，进入{$project['pname']}项目！";
        $msgData = [
            'msg_type' => 1,
            'msg_content' => $msgContent
        ];
        TipMsg::addRecord($msgData);
        unset($user);
        unset($project);
        unset($msgData);

        return json(['msg' => 'success', 'code' => 1]);
    }

    /**
     * 添加职位
     */
    public function addposition()
    {
        if ($this->request->isPost()) {
            $category_id = $this->request->post("category_id", 0, 'intval');
            $projectId = $this->request->param('ids', 0);

            if ($category_id <= 0) {
                $this->error('请选择职位');
            }

            if ($projectId <= 0) {
                $this->error('项目参数错误');
            }

            $row = [
                'project_id' => $projectId,
                'category_id' => $category_id
            ];
            ProjectAssign::addRecord($row);
            unset($row);

            $this->success('success');
        }
        //获取职位列表
        $list = AdminCategoryModel::findListByCondition(['type' => 'default', 'pid' => ['gt', 0]]);
        $listData = [];
        if ($list) {
            foreach ($list as $listVal) {
                $listData[$listVal['id']] = $listVal['name'];
            }
        }
        $listData[0] = '请选择';
        $this->assign('categorydata', $listData);
        return $this->view->fetch('addposition');
    }

    /**
     * 退出该项目
     */
    public function deluser()
    {
        $id = $this->request->param('ids', 0);
        if ($id <= 0) {
            $this->error('参数错误');
        }
        $assign = ProjectAssign::findInfoByCondition(['id' => $id]);
        if (!$assign) {
            $this->error('参数错误');
        }
        ProjectAssign::saveData(['id' => $id], ['work_status' => 3]);

        //判断是否有进行中的项目
        if ($assign['uid'] > 0) {
            $doing = ProjectAssign::findInfoByCondition(['uid' => $assign['uid'], 'work_status' => ['in', [0, 1]]]);
            if (!$doing) {  //如果没有进行中的项目，则变为空闲状态
                User::saveData(['id' => $assign['uid']], ['state' => 0]);
            }
        }

        return json(['msg' => 'success', 'code' => 1]);
    }

    /**
     * 删除记录
     */
    public function delrecord()
    {
        $id = $this->request->param('ids', 0);
        if ($id <= 0) {
            $this->error('参数错误');
        }
        ProjectAssign::saveData(['id' => $id], ['is_del' => 1]);
        return json(['msg' => 'success', 'code' => 1]);
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        $spendProgress = [];
        for($i = 0; $i <= 100; $i++) {
            $spendProgress[] = $i;
        }
        $this->assign('spendProgress', $spendProgress);
        return parent::edit($ids);
    }

    public function editAssign($ids = null)
    {

        $assignId = $this->request->param('ids', 0);

        //获取项目分配记录
        $projectAssign = ProjectAssign::findInfoByCondition(['id' => $assignId]);

        $row = $projectAssign;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['employ_price'] = $params['employ_price'] ? (float)sprintf('%.2f', $params['employ_price']) : 0;
                    if ($params['employ_price'] <= 0) {
                        Db::rollback();
                        $this->error('雇佣价格必须大于0');
                    }
                    ProjectAssign::saveData(['id' => $ids], $params);
                    Db::commit();

                    $result = true;
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->assign('row', $projectAssign);

        return $this->view->fetch('edit_assign');
    }

}
